//
//  YQCalendarView.m
//  calendarDemo
//
//  Created by problemchild on 16/8/22.
//  Copyright © 2016年 ProblenChild. All rights reserved.
//

#define kViewWidth(v)            v.frame.size.width
#define kViewHeight(v)           v.frame.size.height
#define kViewX(v)                v.frame.origin.x
#define kViewY(v)                v.frame.origin.y
#define kViewMaxX(v)             (v.frame.origin.x + v.frame.size.width)
#define kViewMaxY(v)             (v.frame.origin.y + v.frame.size.height)
#define kRectX(f)                f.origin.x
#define kRectY(f)                f.origin.y
#define kRectWidth(f)            f.size.width
#define kRectHeight(f)           f.size.height
#define kRectSetWidth(f, w)      CGRectMake(kRectX(f), kRectY(f), w            , kRectHeight(f))
#define kRectSetHeight(f, h)     CGRectMake(kRectX(f), kRectY(f), kRectWidth(f), h             )
#define kRectSetX(f, x)          CGRectMake(x        , kRectY(f), kRectWidth(f), kRectHeight(f))
#define kRectSetY(f, y)          CGRectMake(kRectX(f), y        , kRectWidth(f), kRectHeight(f))
#define kRectSetSize(f, w, h)    CGRectMake(kRectX(f), kRectY(f), w            , h             )
#define kRectSetOrigin(f, x, y)  CGRectMake(x        , y        , kRectWidth(f), kRectHeight(f))
#define kRect(x, y, w, h)        CGRectMake(x        , y        , w            , h             )

#define kBTNsetAction(btn,function) [btn addTarget:self action:@selector(function) forControlEvents:UIControlEventTouchUpInside];

#import "YQCalendarView.h"

#import "YQCalendarEachDay.h"

@interface YQCalendarView ()

/**
 *  往前BTN
 */
@property (nonatomic,strong) UIButton *preBTN;

/**
 *  往后BTN
 */
@property (nonatomic,strong) UIButton *nextBTN;

/**
 *  日期标题Lable
 */
@property (nonatomic,strong) UILabel  *titleLab;

/**
 *  预加载的一页日历
 */
@property (nonatomic,strong) UIView   *preDayView;

/**
 *  当前显示的一页日历
 */
@property (nonatomic,strong) UIView   *dayView;

/**
 *  显示的年
 */
@property int showYear;
/**
 *  显示的月
 */
@property int showMonth;


@property(nonatomic,strong)NSMutableArray *learnArr;
@property(nonatomic,strong)NSMutableArray *testArr;

@end

@implementation YQCalendarView

-(NSMutableArray *)learnArr{
    if(!_learnArr){
        _learnArr = [NSMutableArray array];
    }
    return _learnArr;
}

-(NSMutableArray *)testArr{
    if(!_testArr){
        _testArr = [NSMutableArray array];
    }
    return _testArr;
}


-(NSMutableArray *)selectedArray{
    if(!_selectedArray){
        _selectedArray = [NSMutableArray array];
    }
    return _selectedArray;
}
-(void)setSelectedArray:(NSArray *)array{
    _selectedArray = [NSMutableArray arrayWithArray:array];
    [self loadData];
}

-(UIColor *)titleColor{
    return _titleColor?_titleColor:UIColorHex(0x222222);
}
-(void)setTitleColor:(UIColor *)color{
    _titleColor = color;
    self.titleLab.textColor = color;
}

-(UIFont *)titleFont{
    return _titleFont?_titleFont:JPUIFontPingFangBold(20);
}
-(void)setTitleFont:(UIFont *)font{
    _titleFont = font;
    self.titleLab.font = font;
}

-(UIColor *)dayColor{
    return _dayColor?_dayColor:KFontBlackColor;
}
-(void)setDayColor:(UIColor *)color{
    _dayColor = color;
    [self loadData];
}

-(UIFont *)dayFont{
    return _dayFont?_dayFont:JPUIFontInterMedium(15);
}
-(void)setDayFont:(UIFont *)font{
    _dayFont = font;
    [self loadData];
}

-(UIColor *)selectedBackColor{
    return _selectedBackColor?_selectedBackColor:KThemeColor;
}
-(void)setSelectedBackColor:(UIColor *)color{
    _selectedBackColor = color;
    [self loadData];
}


-(UIImage *)nextBTNIcon{
    return _nextBTNIcon?_nextBTNIcon:[UIImage imageNamed:@"calendar_next"];
}
-(void)setNextBTNIcon:(UIImage *)img{
    _nextBTNIcon = img;
    [self.nextBTN setImage:self.nextBTNIcon forState:UIControlStateNormal];
}

-(UIImage *)preBTNIcon{
    return _preBTNIcon?_preBTNIcon:[UIImage imageNamed:@"calendar_before"];
}
-(void)setPreBTNIcon:(UIImage *)img{
    _preBTNIcon = img;
    [self.preBTN setImage:self.preBTNIcon forState:UIControlStateNormal];
}


-(instancetype)initWithFrame:(CGRect)frame andWidth:(CGFloat)currentWidth{
    self = [super initWithFrame:frame];
    self.currentAvailableWidth = currentWidth;
    [self SetUp];
    
    return self;
}

#pragma mark - 界面宽度改变时
-(void)refreshWidth{
    // 保存当前的月份和年份
    int currentMonth = self.showMonth;
    int currentYear = self.showYear;
    [self removeAllSubviews];
    [self SetUp];
    // 在刷新后滚动回之前的月份
    [self scrollToMonth:currentMonth year:currentYear];
}

#pragma mark - 滚动到某年某月
- (void)scrollToMonth:(int)month year:(int)year {
    // 更新月份和年份
    self.showMonth = month;
    self.showYear = year;
    
    // 渲染该月份的视图
    CGFloat c_w = [DeviceUtils getAdaptedWidthForDesignWidth:118 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(c_w > 185){
        c_w = 185;
    }
    
    // 渲染出目标月份的视图
    [self setUpTheDayView:self.preDayView
                 ForMonth:self.showMonth
                     Year:self.showYear
                 andFrame:CGRectMake(0, c_w+1, kViewWidth(self), self.frame.size.height-c_w-1-48)];
    
    // 直接更新视图位置，无动画效果
    self.preDayView.frame = CGRectMake(0, c_w+1, kViewWidth(self), self.frame.size.height-c_w-1-48);
    self.dayView.frame = CGRectMake(kViewWidth(self), c_w+1, kViewWidth(self), self.frame.size.height-c_w-1-48);
    
    // 替换当前视图
    UIView *tempview = self.dayView;
    self.dayView = self.preDayView;
    self.preDayView = tempview;
    
    // 清理不再显示的子视图
    for (UIView *subview in self.preDayView.subviews) {
        [subview removeFromSuperview];
    }
    
    // 刷新标签
    [self freshLable];
    
    // 通知代理
    if (self.delegate) {
        [self.delegate YQCalendarViewTouchedNextOrPreMonth:[NSString stringWithFormat:@"%d-%02d", self.showYear, self.showMonth]];
    }
}




#pragma mark - 初始化
-(void)SetUp{
    
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = 10;
    self.layer.masksToBounds = YES;
    
    CGFloat c_top = [DeviceUtils getAdaptedWidthForDesignWidth:58 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(c_top > 85){
        c_top = 85;
    }
    __weak typeof(self)self_weak_ = self;
    UIView *topView = [[UIView alloc]init];
    topView.backgroundColor = [UIColor whiteColor];
    [self addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(@0);
        make.height.mas_equalTo(c_top);
    }];
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = KLineColor;
    [self addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@12);
        make.right.mas_equalTo(@-12);
        make.height.mas_equalTo(@1.0);
        make.top.mas_equalTo(topView.mas_bottom);
    }];
    
    //下个月
    self.nextBTN = [[UIButton alloc]init];
    [self.nextBTN setImage:self.nextBTNIcon forState:UIControlStateNormal];
    kBTNsetAction(self.nextBTN, nextMonth)
    [topView addSubview:self.nextBTN];
    [self.nextBTN mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-7);
        make.width.height.mas_equalTo(@28);
        make.centerY.mas_equalTo(topView);
    }];
    
    //这个月
    self.preBTN = [[UIButton alloc]init];
    [self.preBTN setImage:self.preBTNIcon forState:UIControlStateNormal];
    kBTNsetAction(self.preBTN, preMonth)
    [topView addSubview:self.preBTN];
    [self.preBTN mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@28);
        make.right.mas_equalTo(self_weak_.nextBTN.mas_left).offset(-14);
        make.centerY.mas_equalTo(topView);
    }];
    
    //时间
    self.titleLab = [[UILabel alloc]init];
    self.titleLab.textColor = self.titleColor;
    self.titleLab.font = self.titleFont;
    [topView addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@12);
        make.height.mas_equalTo(@30);
        make.centerY.mas_equalTo(topView);
    }];
    
    CGFloat week_top = [DeviceUtils getAdaptedWidthForDesignWidth:76 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat week_w = [DeviceUtils getAdaptedWidthForDesignWidth:24 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(week_top > 100){
        week_top = 100;
    }
    
    //星期
    NSArray *arr = @[@"月",@"火",@"水",@"木",@"金",@"土",@"日"];
    CGFloat left = 12;
    CGFloat Xmid   = (kRectWidth(self.frame)-24-week_w*7)/6;
    for (NSInteger i = 0; i < arr.count;i++) {
        UILabel *weekLabel = [[UILabel alloc]initWithFrame:CGRectMake(left,week_top+1,week_w,week_w)];
        weekLabel.text = arr[i];
        weekLabel.font = JPUIFontPingFangSCMedium(12);
        weekLabel.textColor = KFontGrayColor;
        weekLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:weekLabel];
        left = left+week_w+Xmid;
    }
    
    UIView *pointView = [[UIView alloc]init];
    pointView.backgroundColor = KThemeColor;
    pointView.layer.cornerRadius = 2.5;
    pointView.layer.masksToBounds = YES;
    [self addSubview:pointView];
    [pointView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@12);
        make.width.height.mas_equalTo(@5);
        make.bottom.mas_equalTo(-20);
    }];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.textColor = KFontBlackColor;
    tipLabel.font = JPUIFontPingFangSCRegular(12);
    tipLabel.text = @"背词打卡标记";
    [self addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(pointView.mas_right).offset(6);
        make.height.mas_equalTo(@17);
        make.centerY.mas_equalTo(pointView);
    }];
    
    UIView *pointView2 = [[UIView alloc]init];
    pointView2.backgroundColor = UIColorHex(0xFF781D);
    pointView2.layer.cornerRadius = 2.5;
    pointView2.layer.masksToBounds = YES;
    [self addSubview:pointView2];
    [pointView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(pointView.mas_right).offset(98);
        make.width.height.mas_equalTo(@5);
        make.bottom.mas_equalTo(-20);
    }];
    UILabel *tipLabel2 = [[UILabel alloc]init];
    tipLabel2.textColor = KFontBlackColor;
    tipLabel2.font = JPUIFontPingFangSCRegular(12);
    tipLabel2.text = @"测词打卡标记";
    [self addSubview:tipLabel2];
    [tipLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(pointView2.mas_right).offset(6);
        make.height.mas_equalTo(@17);
        make.centerY.mas_equalTo(pointView);
    }];
    
    //--------------------------------------------------
    NSDate *date  = [NSDate date];
    NSDateFormatter *Yearformater = [NSDateFormatter new];
    Yearformater.dateFormat = @"yyyy";
    NSString *yearstr = [Yearformater stringFromDate:date];
    
    NSDateFormatter *Monthformater = [NSDateFormatter new];
    Monthformater.dateFormat = @"MM";
    NSString *monthstr = [Monthformater stringFromDate:date];
    
    self.titleLab.text = [NSString stringWithFormat:@"%@年%@月",yearstr,monthstr];
    
    self.showMonth = monthstr.intValue;
    self.showYear = yearstr.intValue;
    
    //--------------------------------------------------
    self.dayView = [[UIView alloc]init];
    self.preDayView = [[UIView alloc]initWithFrame:CGRectZero];
    
    [self loadData];
    
    [self addSubview:self.dayView];
    [self addSubview:self.preDayView];
    
    
    UISwipeGestureRecognizer *swipe1 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(nextMonth)];
    swipe1.direction = UISwipeGestureRecognizerDirectionLeft;
    [self addGestureRecognizer:swipe1];
    
    UISwipeGestureRecognizer *swipe2 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(preMonth)];
    swipe2.direction = UISwipeGestureRecognizerDirectionRight;
    [self addGestureRecognizer:swipe2];
}

/**
 *  加载某个月的显示
 *
 *  @param dayView 显示的View
 *  @param month   月
 *  @param year    年
 *  @param frame   位置
 */
-(void)setUpTheDayView:(UIView *)dayView
              ForMonth:(int)month
                  Year:(int)year
              andFrame:(CGRect)frame{
    dayView.frame = frame;
    
    // 计算当月显示行数
    int numberOfRows = [self numberOfRowsInMonth:month year:year];
    
    //--------------------------------------------------
    NSString* string = [NSString stringWithFormat:@"%4d0%1d01010101",year,month];
    if(month>9){
        string = [NSString stringWithFormat:@"%4d%2d01010101",year,month];
    }
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init] ;
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] ];
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate* inputDate = [inputFormatter dateFromString:string];

    
    //--------------------------------------------------时间格式转换器
    NSDateFormatter *Dayformater = [NSDateFormatter new];
    [Dayformater setLocale:[NSLocale currentLocale]];
    Dayformater.dateFormat = @"dd";
    NSDateFormatter *Monthformater = [NSDateFormatter new];
    [Monthformater setLocale:[NSLocale currentLocale]];
    Monthformater.dateFormat = @"MM";
    NSDateFormatter *EEEformater = [NSDateFormatter new];
    [EEEformater setLocale:[NSLocale currentLocale]];
    EEEformater.dateFormat = @"EEE";
    
    NSDateFormatter *Checkformater = [NSDateFormatter new];
    [Checkformater setLocale:[NSLocale currentLocale]];
    Checkformater.dateFormat = @"yyyy-MM-dd";
    
    //--------------------------------------------------计算位置、间距
    double Ymid   = 0;
    double Xmid   = 0;
    double Height = 0;
    double Width  = 0;
    
    CGFloat week_w = [DeviceUtils getAdaptedWidthForDesignWidth:24 andCurrentAvailableWidth:self.currentAvailableWidth];
    Height = week_w;
    Ymid   = (kRectHeight(frame)-week_w*numberOfRows)/(numberOfRows-1);
    Xmid   = (kRectWidth(frame)-24-week_w*7)/6;
    Width  = week_w;
    
    
    double nowX = Xmid;
    double nowY = 0;
    
    NSString *nowDayEEE = [EEEformater stringFromDate:inputDate];
    
    if([nowDayEEE isEqualToString:@"Mon"]||[nowDayEEE isEqualToString:@"周一"]){
        nowX = 12;
    }else if([nowDayEEE isEqualToString:@"Tue"]||[nowDayEEE isEqualToString:@"周二"]){
        nowX = 12+ Width+Xmid;
    }else if([nowDayEEE isEqualToString:@"Wed"]||[nowDayEEE isEqualToString:@"周三"]){
        nowX = 12 + (Width+Xmid)*2;
    }else if([nowDayEEE isEqualToString:@"Thu"]||[nowDayEEE isEqualToString:@"周四"]){
        nowX = 12 + (Width+Xmid)*3;
    }else if([nowDayEEE isEqualToString:@"Fri"]||[nowDayEEE isEqualToString:@"周五"]){
        nowX = 12 + (Width+Xmid)*4;
    }else if([nowDayEEE isEqualToString:@"Sat"]||[nowDayEEE isEqualToString:@"周六"]){
        nowX = 12 + (Width+Xmid)*5;
    }else if([nowDayEEE isEqualToString:@"Sun"]||[nowDayEEE isEqualToString:@"周日"]){
        nowX = 12 + (Width+Xmid)*6;
    }else{
        nowX = 12;
    }
    
    //判断是否是今天需要
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *todayComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
    NSInteger currentYear = [todayComponents year];
    NSInteger currentMonth = [todayComponents month];
    NSInteger currentDay = [todayComponents day];
    
    //--------------------------------------------------循环加载每一天
    
    while ([Monthformater stringFromDate:inputDate].intValue == month){
        
        NSString *daystr = [Dayformater stringFromDate:inputDate];
        
        //        NSLog(@"%f,%f",nowX,nowY);
        
        YQCalendarEachDay *eachdayView = [[YQCalendarEachDay alloc]
                                            initWithFrame:CGRectMake(nowX,
                                                                     nowY,
                                                                     Width,
                                                                     Height) andWidth:self.currentAvailableWidth];
        
        [eachdayView setTheDay:daystr.intValue];
        eachdayView.dayColor = self.dayColor;
        NSString *formatMonthString = [NSString stringWithFormat:@"%d",month];
        if(month<10){formatMonthString = [NSString stringWithFormat:@"0%d",month];}
        NSString *formatDayString = [NSString stringWithFormat:@"%d",daystr.intValue];
        if(daystr.intValue<10){formatDayString = [NSString stringWithFormat:@"0%d",daystr.intValue];}
        eachdayView.dateString = [NSString stringWithFormat:@"%4d-%@-%@",year,formatMonthString,formatDayString];
        [dayView addSubview:eachdayView];
        
        if (year == currentYear && month == currentMonth && daystr.intValue == currentDay) {
            eachdayView.isToday = YES;
        }else{
            eachdayView.isToday = NO;
        }
        eachdayView.selectedBackColor = self.selectedBackColor;
        NSString *checkString = [Checkformater stringFromDate:inputDate];
        if([self.selectedArray containsObject:checkString]){
            [eachdayView setTheSelectedMode:YES];
        }
        
        //添加背词 测词打卡显示
        BOOL isLearn = [self.learnArr containsObject:eachdayView.dateString];
        BOOL isTest = [self.testArr containsObject:eachdayView.dateString];
        [eachdayView setCalendarIsLearn:isLearn andIsTest:isTest];
        
        //--------------------------------------------------手势
        //添加双击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dayTouched:)];
        //设置出发操作需要的点按次数
        tap.numberOfTapsRequired = 1;
        //设置需要几根手指触发操作
        tap.numberOfTouchesRequired = 1;
        //把手势添加到视图上
        [eachdayView addGestureRecognizer:tap];
        
        //--------------------------------------------------
        inputDate = [NSDate dateWithTimeInterval:24*60*60 sinceDate:inputDate];
        //        NSString *str = [EEEformater stringFromDate:inputDate];
        //        NSLog(@"%@",str);
        if([[EEEformater stringFromDate:inputDate] isEqualToString:@"Mon"] ||
           [[EEEformater stringFromDate:inputDate] isEqualToString:@"周一"])
        {
            nowX = 12;
            nowY = nowY+Height+Ymid;
        }else{
            nowX = nowX+Width+Xmid;
        }
        //        NSLog(@"testDate:%@", str);
    };
}

- (int)numberOfRowsInMonth:(int)month year:(int)year {
    // 获取当月的第一天
    NSString* string = [NSString stringWithFormat:@"%4d0%1d01010101", year, month];
    if (month > 9) {
        string = [NSString stringWithFormat:@"%4d%2d01010101", year, month];
    }
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate* inputDate = [inputFormatter dateFromString:string];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange rangeOfDays = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:inputDate];
    NSUInteger numberOfDaysInMonth = rangeOfDays.length;
    
    // 计算该月的第一天是星期几
    NSDateFormatter *EEEformater = [NSDateFormatter new];
    [EEEformater setLocale:[NSLocale currentLocale]];
    EEEformater.dateFormat = @"EEE";
    NSString *firstDayEEE = [EEEformater stringFromDate:inputDate];
    
    int firstWeekday = 0; // 1 for Monday, 7 for Sunday
    if ([firstDayEEE isEqualToString:@"Mon"] || [firstDayEEE isEqualToString:@"周一"]) {
        firstWeekday = 1;
    } else if ([firstDayEEE isEqualToString:@"Tue"] || [firstDayEEE isEqualToString:@"周二"]) {
        firstWeekday = 2;
    } else if ([firstDayEEE isEqualToString:@"Wed"] || [firstDayEEE isEqualToString:@"周三"]) {
        firstWeekday = 3;
    } else if ([firstDayEEE isEqualToString:@"Thu"] || [firstDayEEE isEqualToString:@"周四"]) {
        firstWeekday = 4;
    } else if ([firstDayEEE isEqualToString:@"Fri"] || [firstDayEEE isEqualToString:@"周五"]) {
        firstWeekday = 5;
    } else if ([firstDayEEE isEqualToString:@"Sat"] || [firstDayEEE isEqualToString:@"周六"]) {
        firstWeekday = 6;
    } else if ([firstDayEEE isEqualToString:@"Sun"] || [firstDayEEE isEqualToString:@"周日"]) {
        firstWeekday = 7;
    }
    
    // 计算总共显示的行数
    int numberOfRows = ((int)numberOfDaysInMonth + firstWeekday - 1) / 7 + (((int)numberOfDaysInMonth + firstWeekday - 1) % 7 > 0 ? 1 : 0);
    
    return numberOfRows;
}



/**
 *  查看下一个月
 */
-(void)nextMonth{
    
    //动画结束前，先禁用按钮
    self.nextBTN.enabled = NO;
    
    self.showMonth+=1;
    if(self.showMonth == 13){
        self.showYear+=1;
        self.showMonth = 1;
    }
    CGFloat c_w = [DeviceUtils getAdaptedWidthForDesignWidth:118 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(c_w > 185){
        c_w = 185;
    }
    //渲染出下一页
    [self setUpTheDayView:self.preDayView
                 ForMonth:self.showMonth
                     Year:self.showYear
                 andFrame:CGRectMake(kViewWidth(self),
                                     c_w+1,
                                     kViewWidth(self),
                                     self.frame.size.height-c_w-1-48)];

    
    //通过动画变过去
    [UIView animateWithDuration:0.5 animations:^{
        
        self.preDayView.frame = kRectSetX(self.preDayView.frame, 0);
        self.dayView.frame    = kRectSetX(self.dayView.frame, -kViewWidth(self));
        
    }completion:^(BOOL finished) {
        
        UIView *tempview = self.dayView;
        
        self.dayView     = self.preDayView;
        self.preDayView  = tempview;
        
        for (UIView *subview in self.preDayView.subviews) {
            [subview removeFromSuperview];
        }
        
        self.nextBTN.enabled = YES;
        
    }];
    
    [self freshLable];
    
    if(self.delegate){
        [self.delegate YQCalendarViewTouchedNextOrPreMonth:[NSString stringWithFormat:@"%d-%02d",self.showYear,self.showMonth]];
    }
    
}

/**
 *  查看前一个月的日历
 */
-(void)preMonth{
    //动画结束前，先禁用按钮
    self.preBTN.enabled = NO;
    
    self.showMonth-=1;
    if(self.showMonth == 0){
        self.showYear-=1;
        self.showMonth = 12;
    }
    CGFloat c_w = [DeviceUtils getAdaptedWidthForDesignWidth:118 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(c_w > 185){
        c_w = 185;
    }
    //渲染出前一页
    [self setUpTheDayView:self.preDayView
                 ForMonth:self.showMonth
                     Year:self.showYear
                 andFrame:CGRectMake(-kViewWidth(self),
                                     c_w+1,
                                     kViewWidth(self),
                                     self.frame.size.height-c_w-1-48)];
    
    //通过动画变过去
    [UIView animateWithDuration:0.5 animations:^{
        
        self.preDayView.frame = kRectSetX(self.preDayView.frame, 0);
        self.dayView.frame = kRectSetX(self.dayView.frame, kViewWidth(self));
        
    }completion:^(BOOL finished) {
        
        UIView *tempview = self.dayView;
        
        self.dayView = self.preDayView;
        self.preDayView = tempview;
        
        for (UIView *subview in self.preDayView.subviews) {
            [subview removeFromSuperview];
        }
        self.preBTN.enabled = YES;
        
    }];
    [self freshLable];
    
    if(self.delegate){
        [self.delegate YQCalendarViewTouchedNextOrPreMonth:[NSString stringWithFormat:@"%d-%02d",self.showYear,self.showMonth]];
    }
    
}

/**
 *  更新日历标题
 */
-(void)freshLable{
    self.titleLab.text = [NSString stringWithFormat:@"%d年%d月",self.showYear,self.showMonth];
}

/**
 *  加载日历显示
 */
-(void)loadData{
    for (UIView *subview in self.dayView.subviews) {
        [subview removeFromSuperview];
    }
    CGFloat c_w = [DeviceUtils getAdaptedWidthForDesignWidth:118 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(c_w > 185){
        c_w = 185;
    }
    [self setUpTheDayView:self.dayView
                 ForMonth:self.showMonth
                     Year:self.showYear
                 andFrame:CGRectMake(0,c_w+1,
                                     kViewWidth(self),self.frame.size.height-c_w-1-48)];
}

//把某一天变为选中状态
-(void)AddToChooseOneDay:(NSString *)dayStr{
    [self.selectedArray addObject:dayStr];
    [self loadData];
}


//点击手势
-(void)dayTouched:(UITapGestureRecognizer *)recognizer{
    NSString *dayString = ((YQCalendarEachDay *)(recognizer.view)).dateString;
    //NSLog(@"%@",dayString);
    if(self.delegate){
        [self.delegate YQCalendarViewTouchedOneDay:dayString];
    }
}

-(void)setCalendarModel:(StudyCalendarModel *)calendarModel{
    _calendarModel = calendarModel;
    if(calendarModel.learnList){
        self.learnArr = [NSMutableArray array];
        for(NSInteger i = 0 ;i < calendarModel.learnList.count;i++){
            NSDictionary *dic = calendarModel.learnList[i];
            NSString *createTime = [NSString stringWithFormat:@"%@",dic[@"createTime"]];
            NSArray *arr = [createTime componentsSeparatedByString:@" "];
            if(arr.count > 0){
                [self.learnArr addObject:arr[0]];
            }
        }
    }
    
    if(calendarModel.testList){
        self.testArr = [NSMutableArray array];
        for(NSInteger i = 0 ;i < calendarModel.testList.count;i++){
            NSDictionary *dic = calendarModel.testList[i];
            NSString *createTime = [NSString stringWithFormat:@"%@",dic[@"createTime"]];
            NSArray *arr = [createTime componentsSeparatedByString:@" "];
            if(arr.count > 0){
                [self.testArr addObject:arr[0]];
            }
        }
    }
    
    [self refreshPointUI];
    
}


-(void)refreshPointUI{
    
    if(self.dayView){
        for (UIView *subview in self.dayView.subviews) {
            if ([subview isKindOfClass:[YQCalendarEachDay class]]) {
                YQCalendarEachDay *eachdayView = (YQCalendarEachDay *)subview;
                NSString *dateString = eachdayView.dateString; // @"yyyy-MM-dd" 格式
                BOOL isLearn = [self.learnArr containsObject:dateString];
                BOOL isTest = [self.testArr containsObject:dateString];
                [eachdayView setCalendarIsLearn:isLearn andIsTest:isTest];
            }
        }
    }
   
    if(self.preDayView){
        for (UIView *subview in self.preDayView.subviews) {
            if ([subview isKindOfClass:[YQCalendarEachDay class]]) {
                YQCalendarEachDay *eachdayView = (YQCalendarEachDay *)subview;
                NSString *dateString = eachdayView.dateString; // @"yyyy-MM-dd" 格式
                BOOL isLearn = [self.learnArr containsObject:dateString];
                BOOL isTest = [self.testArr containsObject:dateString];
                [eachdayView setCalendarIsLearn:isLearn andIsTest:isTest];
            }
        }
    }
    
}

@end
